package com.tzjw.service;

import com.tzjw.bean.MarketStorage;
import com.tzjw.mapper.MarketStorageMapper;
import com.tzjw.util.MyBatisUtil;
import lombok.SneakyThrows;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

public class AdminStorageServiceImpl implements AdminStorageService {
    @SneakyThrows
    public MarketStorage saveAndCreateRecord(String storagePath, Part part)  {
        InputStream inputStream = part.getInputStream();
        // 原始的文件名
        String submittedFileName = part.getSubmittedFileName();

        String suffix = submittedFileName.substring(submittedFileName.lastIndexOf("."));// .jpg .png
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String wholeFileName = fileName + suffix;

        File file = new File(storagePath, wholeFileName);
        FileOutputStream outputStream = new FileOutputStream(file);

        byte[] bytes = new byte[1024];
        int len;
        while ((len = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        outputStream.close();

        MarketStorage marketStorage = MarketStorage.builder()
                .key(wholeFileName)
                .name(submittedFileName)
                .size((int) part.getSize())
                .type(part.getContentType())
                .url("http://localhost:8083/wx/storage/fetch/" + wholeFileName)
                .addTime(new Date())
                .updateTime(new Date())
                .build();
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketStorageMapper mapper = sqlSession.getMapper(MarketStorageMapper.class);
        mapper.insert(marketStorage);
        return marketStorage;
    }
}
